import { baseUrl, wxdomian } from './env'

export default async(url, options, isWxdomain) => {
  options = options || {}
  options.type = options.type || 'GET'
  options.method = options.method || 'fetch'
  options.data = options.data || {}
  options.headers = options.headers || {}
  options.contentType = options.contentType || false

  let baseHeaders = {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
    // 'Content-Type': 'application/json'
  }
  options.headers = {...baseHeaders, ...options.headers}
  if (options.contentType === 'json') {
    options.headers['Content-Type'] = 'application/json'
  }

  // options.method = 'ajax'
  if (isWxdomain) {
    url = wxdomian + url
  } else {
    url = baseUrl + url
  }
  // https://api.snb.pub

  if (options.type === 'GET') {
    let dataStr = '' // 数据拼接字符串
    Object.keys(options.data).forEach(key => {
      dataStr += key + '=' + options.data[key] + '&'
    })
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr
    }
  }

  // if (window.fetch && options.method === 'fetch') {
  if (window.fetch && options.method === 'fetch') {
    let requestConfig = {
      // credentials: 'include',
      method: options.type,
      headers: options.headers,
      mode: 'cors',
      cache: 'force-cache'
    }
    if (options.contentType) {
      Object.defineProperty(requestConfig, 'body', {
        value: JSON.stringify(options.data)
      })
    } else if (options.type === 'POST' && typeof options.data === 'object') {
      let arrs = []
      for (let k in options.data) {
        arrs.push(k + '=' + options.data[k])
      }
      Object.defineProperty(requestConfig, 'body', {
        value: arrs.join('&')
      })
      // console.log(JSON.stringify(options.data))
    }
    try {
      var response = await fetch(url, requestConfig)
      var responseJson = await response.json()
    } catch (error) {
      throw new Error(error)
    }
    // console.log('请求状态值：' + response.status)
    // console.log(responseJson)
    return responseJson
  } else {
    let requestObj
    if (window.XMLHttpRequest) {
      requestObj = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
      let ActiveXObject = window.ActiveXObject
      requestObj = new ActiveXObject('Microsoft.XMLHTTP')
    }

    let sendData = ''
    if (options.contentType) {
      sendData = JSON.stringify(options.data)
    } else if (options.type === 'POST') {
      // sendData = JSON.stringify(options.data)
      if (typeof options.data === 'object') {
        let arrs = []
        for (let k in options.data) {
          arrs.push(k + '=' + options.data[k])
        }
        sendData = arrs.join('&')
      }
    }
    requestObj.open(options.type, url, true)

    Object.keys(options.headers).forEach(key => {
      requestObj.setRequestHeader(key, options.headers[key])
    })
    // requestObj.setRequestHeader('Accept', 'application/json')
    // requestObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    requestObj.send(sendData)
    let ajaxStateChangeApi = () => {
      return new Promise((resolve, reject) => {
        requestObj.onreadystatechange = () => {
          if (requestObj.readyState === 4) {
            // if (requestObj.status === 200) {
            if (requestObj.status >= 200 && requestObj.status < 300) {
              let obj = requestObj.response
              try {
                obj = (typeof obj !== 'object') ? JSON.parse(obj) : obj
              } catch (error) {
                reject(error)
              }
              if (obj) {
                resolve(obj, requestObj.status, requestObj)
              }
            } else {
              // throw new Error(requestObj)
              reject(requestObj)
            }
            // console.log('请求状态值：' + requestObj.status)
          }
        }
      })
    }
    try {
      var responseAjaxJson = await ajaxStateChangeApi()
    } catch (error) {
      throw new Error(error)
    }
    return responseAjaxJson
  }
}

